package com.nd.android.musicboxlibrary.ui.vip.decode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;

import com.nd.android.musicboxlibrary.business.bean.FileInfo;

public class MusicDecoder {

	private static final String KEY = "ACF5213F6E0B445b974C3FFB0013452B";

	public static boolean xxteaDecrypt(String srcFilePath, String destFilePath) {
		File srcFile = new File( srcFilePath );
		File destFile = new File( destFilePath );
		return xxteaDecrypt(srcFile, destFile, KEY);
	}
	
	public static boolean xxteaDecrypt(File srcFile, File destFile) {
		return xxteaDecrypt(srcFile, destFile, KEY);
	}

	private static boolean xxteaDecrypt(File srcFile, File destFile, String key) {
		boolean breturn = false;

		if (destFile.exists()) {
			destFile.delete();
		}

		FileInputStream fis = null;
		FileOutputStream writer = null;
		try {
			fis = new FileInputStream(srcFile);
			int byteread = 0;
			int offset = 0;
			int size = fis.available();
			byte[] a = new byte[size - 1];
			byte[] type = new byte[1];
			byteread = fis.read(type, 0, 1);
			while (offset < size - 1) {
				if ((size - offset) >= 1024)
					byteread = fis.read(a, offset, 1024);
				else
					byteread = fis.read(a, offset, size - offset - 1);
				offset += byteread;
			}

			byte[] buffer = XXTEA.decrypt(a, key.getBytes());
			if (!destFile.exists())
				destFile.createNewFile();
			writer = new FileOutputStream(destFile);
			writer.write(buffer);
			writer.flush();
			breturn = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XXTEAException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null)
					fis.close();
				if (writer != null)
					writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return breturn;
	}
	
	public static String getEncryptedMusicPath(Context context, String musicName) {
		return FileInfo.getEncryptedMusicPath( context ) + File.separator + musicName + FileInfo.EXT_MP3;
	}
}
